package com.liujit.bms.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liujit.bms.admin.domain.model.BlogArticleLabel;
import com.liujit.bms.admin.domain.model.BlogLabel;
import com.liujit.bms.admin.domain.params.BlogArticleLabelParams;
import com.liujit.bms.admin.mapper.BlogArticleLabelMapper;
import com.liujit.bms.admin.service.BlogArticleLabelService;
import com.liujit.bms.admin.service.BlogLabelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 博客文章标签Service实现类
 * @Author liujun
 * @Date 2021-07-03 14:36:28
 */
@Service
public class BlogArticleLabelServiceImpl extends ServiceImpl<BlogArticleLabelMapper, BlogArticleLabel>
        implements BlogArticleLabelService {

    private BlogLabelService blogLabelService;

    @Autowired
    public void setBlogLabelService(BlogLabelService blogLabelService) {
        this.blogLabelService = blogLabelService;
    }

    @Override
    public List<Long> getLabelIdByArticleId(Long articleId) {
        LambdaQueryWrapper<BlogArticleLabel> wrapper = new LambdaQueryWrapper();
        wrapper.select(BlogArticleLabel::getLabelId);
        wrapper.eq(BlogArticleLabel::getArticleId, articleId);
        return super.listObjs(wrapper, item -> Convert.toLong(item));
    }

    @Override
    public List<String> getLabelNameByArticleId(Long articleId) {
        List<Long> ids = this.getLabelIdByArticleId(articleId);
        if (CollectionUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        LambdaQueryWrapper<BlogLabel> wrapper = new LambdaQueryWrapper();
        wrapper.select(BlogLabel::getName);
        wrapper.in(BlogLabel::getId, ids);
        return blogLabelService.listObjs(wrapper, item -> Convert.toStr(item));
    }

    @Override
    public Boolean save(BlogArticleLabelParams params) {
        LambdaQueryWrapper<BlogArticleLabel> wrapper = new LambdaQueryWrapper();
        wrapper.eq(BlogArticleLabel::getArticleId, params.getArticleId());
        Boolean result = super.remove(wrapper);
        // 添加
        List<BlogArticleLabel> list = new ArrayList<>();
        List<Long> labelIds = params.getLabelIds();
        if (CollectionUtil.isNotEmpty(labelIds)) {
            labelIds.forEach(item -> {
                list.add(new BlogArticleLabel() {{
                    setArticleId(params.getArticleId());
                    setLabelId(item);
                }});
            });
        }
        if (CollectionUtil.isNotEmpty(list)) {
            return super.saveBatch(list);
        }
        return result;
    }
}
